package com.example.dem10;

import java.util.Arrays;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: xian-cheng
 * @description:
 * @author: 诸葛龙辰
 * @create: 2022-11-01 20:24
 **/
public class TestSafePig {
    private static String [] arr=new String[3];
    private static int index=0;
    private static Object lock=new Object();
    public static void main(String[] args) throws InterruptedException {
        //创建锁对象
        Lock lock = new ReentrantLock();
        //匿名实现类
        Thread t1=new Thread(new Runnable() {

            @Override
            public void run() {
                try{
                    //手动加锁
                    lock.lock();
                    if (arr[index] == null) {
                        arr[index] = "heihei";
                        index++;
                    }
                }finally {
                    //释放锁
                    lock.unlock();
                }

            }
        });


        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    //手动加锁
                    lock.lock();
                    if (arr[index] == null) {
                        arr[index] = "haha";
                        index++;
                    }
                }finally {
                    //释放锁
                    lock.unlock();
                }

            }
        });
        Thread t3=new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    //手动加锁
                    lock.lock();
                    if (arr[index] == null) {
                        arr[index] = "haha";
                        index++;
                    }
                }finally {
                    //释放锁
                    lock.unlock();
                }

            }
        });

        t1.start();
        t2.start();
        t3.start();

        //不能直接打印arr,因为main线程可能先获取cpu
        t1.join();
        t2.join();
        t3.join();
        System.out.println(Arrays.toString(arr));
    }

}
